package com.andy.android.usbmanager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle.Event;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import com.andy.android.usbmanager.log.LogCall;

public class USBReceiver extends BroadcastReceiver implements LifecycleEventObserver {
    public static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    public void registerLifecycleObserver(LifecycleOwner owner) {
        owner.getLifecycle().addObserver(USBReceiver.this);
        if (owner instanceof Context) {
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            ((Context) owner).registerReceiver(this, filter);
        }
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (ACTION_USB_PERMISSION.equals(action)) {
            // 获取权限结果的广播
            synchronized (this) {
                if (device != null) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        LogCall.d("获取权限成功：" + device.getDeviceName());
                        USBMan.INSTANCE.initUsbDevice(context);
                    } else {
                        LogCall.d("获取权限失败：" + device.getDeviceName());
                    }
                }
            }
        } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            // 有新的设备插入了，在这里一般会判断这个设备是不是我们想要的，是的话就去请求权限
            LogCall.d("设备插入了" + device.getDeviceName());
            int VID = device.getVendorId();
            int PID = device.getProductId();

            if (VID == 1155 && PID == 22352) {
                LogCall.d("--->识别到H10B");
                USBMan.INSTANCE.initUsbDevice(context);
            }

        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            // 有设备拔出了
            LogCall.d("设备拔出了" + device.getDeviceName());
            USBMan.INSTANCE.stopReading();
        }
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        switch (event) {
            case ON_DESTROY:
                if (source instanceof Context) {
                    ((Context) source).unregisterReceiver(this);
                }
            case ON_CREATE:

                break;
        }
    }
}